package com.levi.distributedlock.redisson;

import lombok.extern.slf4j.Slf4j;
import org.redisson.RedissonLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@Slf4j
@RequestMapping("/redisson")
public class RedissonController {
    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/secKill")
    public void secKill() {
        RLock lock = redissonClient.getLock("lock");
        try {
            lock.lock();
            log.info("{}抢到了锁", Thread.currentThread().getName());
            Thread.sleep(3000);
            log.info("{}释放了锁", Thread.currentThread().getName());
            lock.unlock();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/secKillTry")
    public void secKillTry() {
        RLock lock = redissonClient.getLock("lock");

        try {
            /**
             * tryLock的两个参数     FIXME 推荐使用tryLock  效率高还可以防止死锁
             * 尝试获取锁，会等待2秒钟，等待两秒没有获取锁就返回false
             * 锁10秒强制释放，防止死锁
             */
            if (lock.tryLock(2, 10, TimeUnit.SECONDS)) {
                log.info("{}获取到了锁",Thread.currentThread().getName());
                Thread.sleep(2000);
                lock.unlock();
            }else {
                log.info("{}没有获得锁",Thread.currentThread().getName());
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    @GetMapping("redLock")
    public void redLock() {
        RedissonLock redLock = redissonClient.
    }
}

